package org.example.search;

//二分查找算法
public class BinarySearch {
    public static void main(String[] args) {
        int[] arr = {10, 22, 35, 47, 51, 64, 78, 83, 91, 99};
        int target = 47;
        int m1 = binarySearch1(arr, target);
        System.out.println(m1);
        int m2 = binarySearch2(arr, target);
        System.out.println(m2);
    }

    //查找升序数组的二分查找
    public static int binarySearch1(int[] arr, int target) {
        int m = -1;
        int left = 0;
        int right = arr.length - 1;
        while (left <= right) {
            //无符号右移一位操作代替除以2
            int mid = (left + right) >>> 1;
            if (arr[mid] == target) {
                m = mid;
                break;
            } else if (target < arr[mid]) {
                right = mid - 1;
            } else if (arr[mid] < target) {
                left = mid + 1;
            }
        }
        return m;
    }

    //简化代码
    public static int binarySearch2(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;
        while (left <= right) {
            int mid = (left + right) >>> 1;
            if (arr[mid] == target) {
                //直接return
                return mid;
            } else if (target < arr[mid]) {
                right = mid - 1;
            } else if (target > arr[mid]) {
                left = mid + 1;
            }
        }
        return -1;
    }
}
